//
//  HomeViewController.swift
//  微博
//
//  Created by mac on 15/12/12.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

let HomeCellId = "HomeCell"

class HomeViewController: BaseViewController {

    //创建模型数组
    private var statuses = [Status]()
    //创建cellid
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !base  {
        baseView.showBaseView("登录后，别人评论你的微博，发给你的消息，都会在这里收到通知", rutationImage: nil)
            return
        }
        
        
        //基本属性
       prepareTableView()
        
//        loadData() 
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //刷新数据
        loadData()
    }
    
    private func prepareTableView() {
        //1.注册cell
        tableView.registerClass(HomeCell.self, forCellReuseIdentifier: HomeCellId)
        //设置行高
//        tableView.rowHeight = 100
        //设置自动行高
        tableView.estimatedRowHeight = 300
        tableView.rowHeight = UITableViewAutomaticDimension
        //设置分割线
        tableView.separatorStyle = .None
        //添加控件
//        let refresh = RefreshControl()
        tableView.addSubview(refreshView)
        //监听数据
        refreshView.addTarget(self, action: "loadNewData", forControlEvents: .ValueChanged)
        //设置footView为小转轮
        tableView.tableFooterView = indicatorView
        //设置返回数据的label
        navigationController?.navigationBar.addSubview(dataLabel)
        navigationController?.navigationBar.insertSubview(dataLabel, atIndex: 0)
    }
    
    //加载数据
    @objc private func loadNewData() {
        //下拉获取数据和上拉数据只能获取一个
        var since_id:Int64 = 0
        var max_id:Int64 = 0
        //获取第一个数据的id
        //判断是上拉刷新还是下拉刷新,根据小转轮的动画
        if indicatorView.isAnimating() {
            max_id = statuses.last?.id ?? 0
        }else{
        since_id = statuses.first?.id ?? 0
        }
        //加载网络请求
        HomeStatusViewMedol().loadStatus(since_id, max_id: max_id) { (statues) -> () in
            //当网络数据加载完毕之后,关闭动画
            self.refreshView.endRefreshing()
            guard let list = statues else {
                return
            }
            
            if since_id > 0 {
                self.statuses = list + self.statuses
                self.dataLabel.text = list.count == 0 ? "没有新微博" : "加载\(list.count)条微博"
                //设置transform
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.dataLabel.transform = CGAffineTransformMakeTranslation(0, 108)
                    }, completion: { (_) -> Void in
                       UIView.animateWithDuration(0.25, delay: 1, options: [], animations: { () -> Void in
                            self.dataLabel.transform = CGAffineTransformIdentity
                        }, completion: { (_) -> Void in
                                print("ok")
                       })
                })
            }else if max_id > 0 {
                self.statuses = self.statuses + list
                //当添加数据后让转轮关闭动画要不然只能添加一条数据
                self.indicatorView.stopAnimating()
            }else{
                //首次加载
                self.statuses = list
            }
            //刷新页面
            self.tableView.reloadData()
        }
    }
    
    //请求网络数据
    private func loadData() {
        HomeStatusViewMedol().loadStatus(0, max_id: 0) { (statues) -> () in
            if let sta = statues {
                self.statuses = sta
                self.tableView.reloadData()
            }else{
                print("home数据出错")
            }
        }
       
    }
    //定义基本属性
    private lazy var dataLabel:UILabel = {
        let lb = UILabel(frame: CGRect(x: 0, y: -64, width: screenWidth, height: 44))
        lb.text = ""
        lb.backgroundColor = UIColor.orangeColor()
        lb.textAlignment = .Center
        lb.font = UIFont.systemFontOfSize(17)
        lb.textColor = UIColor.whiteColor()
        return lb
    }()
    
    private lazy var refreshView:RefreshControl = RefreshControl()
    //添加foot的小转轮
    private lazy var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
}


//数据源方法
extension HomeViewController {
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    //设置行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print(statuses.count)
        return statuses.count
    }
//    设置cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //设置cell
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath) as! HomeCell
        
//        cell.textLabel?.text = statuses[indexPath.row].text
        cell.status = statuses[indexPath.row]
//        print(statuses[indexPath.row])
        //判断当到底部,且转轮没有转的时候,调用loadNewdat方法加载数据
        if indexPath.row == statuses.count - 1 && !indicatorView.isAnimating() {
            //让小转轮开始转
            indicatorView.startAnimating()
            //加载数据
            loadNewData()
        }
        
        return cell
    }

    
        
}


